import { useDialog, useMessage } from 'naive-ui'

interface ListHookOption {
  /** 分页 */
  isPage: boolean
  /** 默认请求 */
  startQuery: boolean
  /** 请求路径 */
  reqUrl: string
  /** 删除路径 */
  delUrl: string
  /** 搜索条件 */
  queryParams: Record<string, any>
  /** 查询后执行 */
  afterQuery?: (list: any[]) => void
}
/**
 * 查询列表
 * @param fn 查询的方法
 * @param params 参数
 * @returns 总数、列表
 */
export const useList = <T = any>(customOption: Partial<ListHookOption> = {}) => {
  const dialog = useDialog()
  const message = useMessage()
  // 总数
  const total = ref(0)

  const option = ref<ListHookOption>({
    isPage: true,
    startQuery: true,
    reqUrl: '',
    delUrl: '',
    queryParams: {
      pageNum: 1,
      pageSize: 10
    }
  })
  // 列表
  const list = debounceRef([], 1000) as Ref<T[]>
  // 当前页
  const pageNum = ref(1)
  // 每页条数
  const pageSize = ref(10)
  // 加载状态
  const loading = ref(false)

  // 获取列表参数
  async function handleQuery() {
    const { reqUrl } = option.value
    if (!reqUrl) return
    try {
      loading.value = true
      const res = await http.get<ListRes<T> | T>(reqUrl, {
        pageNum: pageNum.value,
        ...option.value.queryParams
      })
      if (option.value.isPage) {
        const { total: totalRes, list: listRes } = res.data as ListRes<T>
        total.value = totalRes
        list.value = listRes
        loading.value = false
        return (res.data as ListRes<T>)?.list
      } else {
        list.value = res.data as T[]
        loading.value = false
        return res.data
      }
    } catch (e) {
      loading.value = false
    }
  }

  // 更新列表后查询
  function query() {
    total.value = 1
    handleQuery()
  }

  // 删除数据
  function handleDel(id: number) {
    dialog.create({
      title: '提示',
      content: '是否确认删除数据？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        http.delete(`${option.value.reqUrl}/${id}`).then(() => {
          message.success('删除成功')
          handleQuery()
        })
      }
    })
  }
  onMounted(async () => {
    if (option.value.startQuery) {
      const list = await handleQuery()
      if (option.value.afterQuery) {
        option.value.afterQuery(list)
      }
    }
  })

  mergeObject(option.value, customOption)
  watch([pageNum, pageSize], () => handleQuery())

  return {
    total,
    list,
    pageNum,
    pageSize,
    handleQuery,
    query,
    handleDel,
    queryParmas: option.value.queryParams
  }
}
